package mysqlredis;

import org.example.Publish;
import redis.clients.jedis.Jedis;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.List;
import java.util.Random;

public class MySQLRedisDemo {
    Connection conn;
    Jedis jedis;
    Random rnd = new Random();

    private void Init(){
        String mySqlDriver = "com.mysql.cj.jdbc.Driver";
        String mySqlUrl = "jdbc:mysql://localhost:3306/redisdemo";

        try{
            Class.forName(mySqlDriver);
            conn= DriverManager.getConnection(mySqlUrl,"root","");
            jedis = new Jedis("localhost",6379);
        }
        catch(Exception e){
            e.printStackTrace();
        }
    }


    public MySQLRedisDemo(){
        Init();
    }

    public void Close(){
        try{
            if(jedis!=null && !jedis.isConnected()){
                jedis.close();
            }
            if(conn!=null && !conn.isClosed()){
                conn.close();
            }
        }
        catch(Exception e){
            e.printStackTrace();
        }
    }

    public Student getStudentById(int id){
        String key="Stu:"+id;
        Student stu=new Student();

        if(jedis.exists(key)){
            System.out.println("ID:"+key+"存在于redis中");
            List<String> list=jedis.lrange(key,0,-1);
            stu.setId(id);
            stu.setName(list.get(0));
            stu.setAge(Integer.valueOf(list.get(1)));
            stu.setScore(Float.valueOf(list.get(2)));
            return stu;
        }
        else {
            System.out.println("ID:"+key+"不存在于redis中");
            PreparedStatement ps=null;

            try {
                ps = conn.prepareStatement("select * from student where id=?");
                ps.setInt(1,id);
                ResultSet rs=ps.executeQuery();
                if(rs.next()){
                    System.out.println("ID:"+key+"存在于mysql中");
                    stu.setId(id);
                    String Name=rs.getString("name");
                    stu.setName(rs.getString("name"));
                    int Age=rs.getInt("age");
                    stu.setAge(rs.getInt("age"));
                    int Score=rs.getInt("score");
                    stu.setScore(rs.getFloat("score"));

                    jedis.rpush(key,Name,Integer.valueOf(Age).toString(),Float.valueOf(Score).toString());
                    jedis.expire(key,60*60+rnd.nextInt(6));
                    return stu;
                }
                else {
                    System.out.println("ID:"+key+"不存在于mysql和redis中");
                    jedis.rpush(key,"null","0","0");
                    jedis.expire(key,60*60+rnd.nextInt(6));
                    return null;
                }
            }catch(Exception e){
                e.printStackTrace();
            }
        }
        return null;
    }

}
